import os
from pathlib import Path

from rosa.scarborough_fair.generator_setting.logger_config import get_logger
from rosa.scarborough_fair.generator_setting.web_filter_tables import WHITE_LIST
from rosa.utils import gen_random_key_string

try:
    from settings import BASE_DIR, Settings as CustomSettings
except ImportError:
    # 获取环境变量ROSE_TEST，如果为True则使用测试环境配置，否则直接抛出异常
    rosa_test = os.getenv("ROSA_TEST")
    if rosa_test != "1":
        raise ImportError("请保证settings.py文件存在并且配置正确")

    from rosa.rosa_settings import BASE_DIR, Settings as CustomSettings

PROJECT_NAME = BASE_DIR.name
SITE_NAME = PROJECT_NAME
STATIC_URL = "/static"
STATIC_PATH = BASE_DIR / "static"
ENV = "develop"

env_file_absolute_path = BASE_DIR.parent / ".env"


class Settings(CustomSettings):
    """
    基础配置
    """
    SITE_NAME: str = SITE_NAME
    BASE_DIR: Path = BASE_DIR
    PROJECT_NAME: str = PROJECT_NAME
    # 雪花算法使用的机器ID和数据中心ID
    SERVER_ID: int = 0
    DATACENTER_ID: int = 0
    # 静态文件路径
    STATIC_URL: str = STATIC_URL
    STATIC_PATH: Path = STATIC_PATH
    ENV: str = ENV
    # token相关
    SECRET_KEY: str = gen_random_key_string()
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 180
    # 全局路由前缀
    URL_PREFIX: str = '/api'
    # 是否开启权限验证
    PERMISSION_ENABLE: bool = False
    # 时区设置
    TIMEZONE: str = 'Asia/Shanghai'

    """
    跨域配置
    """
    # **一个**正则表达式字符串，匹配的源允许跨域请求，例如 'https://.*\.example\.org'。
    CORS_ALLOW_ORIGIN_REGEX: str | None = None
    # 允许的源列表（由字符串组成），先匹配正则
    CORS_ALLOW_ORIGINS: list[str] = []
    # 允许跨域请求支持 cookies。默认是 False。
    # 允许凭证时 allow_origins 不能设定为 ['*']，必须指定源。
    CORS_ALLOW_CREDENTIALS: bool = False
    # 允许的 HTTP 方法（POST，PUT）或者使用通配符 "*" 允许所有方法。默认为 ['GET']。
    CORS_ALLOW_METHODS: list[str] = ['GET']
    # 允许的 HTTP headers 或者使用通配符 "*" 允许所有 headers。默认为 []。
    CORS_ALLOW_HEADERS: list[str] = []
    # 浏览器访问的响应头。默认为 []。
    CORS_EXPOSE_HEADERS: list[str] = []
    # 浏览器缓存 CORS 响应的最长时间，单位是秒。默认为 600
    CORS_MAX_AGE: int = 600

    """
    docs（swagger）文档设置
    """
    OPENAPI_URL: str = "/openapi.json"
    DOCS_URL: str = "/docs"
    REDOC_URL: str = "/redoc"
    SITE_TITLE: str = "平台"
    SITE_DESCRIPTION: str = SITE_TITLE
    DOCS_VERSION: str = "2312"
    SWAGGER_FAVICON_URL: str = ""
    SWAGGER_JS_URL: str = ""
    SWAGGER_CSS_URL: str = ""
    REDOC_FAVICON_URL: str = ""
    REDOC_JS_URL: str = ""
    TERMS_OF_SERVICE: str = ""
    CONTACT_NAME: str = ""
    CONTACT_URL: str = ""
    CONTACT_EMAIL: str = ""
    LICENSE_NAME: str = ""
    LICENSE_URL: str = ""

    """
    web设置
    """
    WEB_TITLE: str = SITE_TITLE
    WEB_DESCRIPTION: str = SITE_DESCRIPTION
    WEB_VERSION: str = DOCS_VERSION
    WEB_WHITE_TABLE: dict[str, list[str]] = WHITE_LIST

    """
    认证设置
    """
    # 是否开启认证
    AUTH_ENABLE: bool = False
    # 是否开启认证相关路由
    AUTH_ROUTER_ENABLE: bool = False
    # 认证类型
    # remote 远程认证
    # local 本地认证，默认类型
    AUTH_TYPE: str = 'local'
    # 认证地址
    AUTH_URL: str = ''
    # 认证用户地址
    AUTH_USERNAME_URL: str = '/api/admin/user'
    AUTH_PASSWORD_URL: str = '/api/admin/user/auth'

    # 当前项目认证token
    AUTH_TOKEN: str = ''

    """
    database设置
    """
    DB_ENABLE: bool = False
    DB_ENGINE: str = 'mysql+aiomysql'
    DB_HOST: str = '127.0.0.1'
    DB_PORT: int = 3306
    DB_USER: str = 'user'
    DB_PASSWORD: str = 'password'
    DB_DATABASE: str = 'master'
    DB_MINSIZE: int = 1
    DB_MAXSIZE: int = 5
    DB_CHARSET: str = 'utf8mb4'
    DB_ECHO: bool = True
    DB_USE_TZ: bool = False
    DB_TIMEZONE: str = 'Asia/Shanghai'
    # 是否进行真实删除，为 False 时进行软删除，只修改名称以及状态
    REAL_DELETE: bool = False

    """
    cache设置,目前只支持redis
    """
    CACHE_ENABLE: bool = False
    CACHE_HOST: str = '127.0.0.1'
    CACHE_PORT: str = '6379'
    CACHE_DB: str = '0'
    CACHE_CHARSET: str = 'utf-8'
    CACHE_USERNAME: str = ''
    CACHE_PASSWORD: str = ''

    """
    日志设置
    """
    LOG_LEVEL: str = 'INFO'
    LOG_DIR: str = 'logs'

    """
    自关闭设置
    """
    # 是否进行开启，目前仅支持使用supervisor启动的程序
    SELF_CLOSE_ENABLE: bool = False
    # 多长时间未访问则进行关闭
    AFTER_SECONDS: int = 600

    class Config:
        env_file = env_file_absolute_path


settings = Settings()
logger = get_logger(settings.LOG_LEVEL, settings.BASE_DIR / settings.LOG_DIR, settings.PROJECT_NAME)
